{
  "properties" : { },
  "id" : "cca9344c160f42899bab708979fbb1c5",
  "script" : null,
  "groupId" : "ea55584b076149d0b62e309b156a9202",
  "name" : "organization.html",
  "createTime" : null,
  "updateTime" : 1739462182294,
  "lock" : null,
  "createBy" : null,
  "updateBy" : "管理员",
  "path" : "organization.html"
}
================================
<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>单位管理系统</title>
    <link rel="stylesheet" href="/plugs/layui/css/layui.css" />
    <style>
      html, body {
        height: 100%
      }
      .layui-table .layui-form-select .layui-input{
        height: 28px
      }
    </style>
</head>
<body class="layui-padding-2">
  <table class="layui-hide" id="ID-treeTable"></table>

  <script type="text/html" id="TPL-select-status">
    {{#  var statusList = ["停用","启用"]; }}
    <select name="status" lay-filter="select-status" lay-append-to="body">
      {{#  layui.each(statusList, function(i, v){ }}
      <option value="{{= i }}" {{= i === d.status ? 'selected' : '' }} >{{= v }}</option>
      {{#  }); }}
    </select>
  </script>
  <script type="text/html" id="TPL-select-roles">
    <select name="roles" lay-filter="select-role" unitId="{{= d.unitId }}" userId="{{= d.userId }}" lay-append-to="body">
      {{#  layui.each(roles, function(i, v){  }}
      <option value="{{= v.value }}" {{= v.value === d.roleId ? 'selected' : '' }} >{{= v.label }}</option>
      {{#  }); }}
    </select>
  </script>
  <script type="text/html" id="TPL-userTable-checkbox">
    {{# if(d.isAssigned) { }}
    <input type="checkbox" disabled title="已分配">
    {{# } else { }}
    <input type="checkbox" name="userId" value="{{d.userId}}" title="选择">
    {{# } }}
  </script>
  <script type="text/html" id="TPL-treeTable-toolbar">
    <div class="layui-btn-container">
      <button class="layui-btn layui-btn-sm" lay-event="addRow">添加</button>
    </div>
  </script>
  <script type="text/html" id="TPL-treeTable-tools">
    <div class="layui-btn-container">
      <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="addChild">添加</a>
      <a class="layui-btn layui-btn-red layui-btn-xs" lay-event="removeRow">删除</a>
    </div>
  </script>

  <script src="/plugs/layui/layui.js"></script>
  <script type="text/javascript">
    layui.use(function(){
      var treeTable = layui.treeTable;
      var table = layui.table;
      var layer = layui.layer;
      var form = layui.form;
      var $ = layui.jquery;

      var userTable = {};
      var roles = [];
      
      var tableId = 'ID-treeTable';
      var userTableId = 'ID-userTable';

      var getRoles = function(){
        $.ajax({
          url: '/api/system/unit/roles', type: 'GET',
          success: function(res){
            window.roles = roles = res.data;
          }
        })
      }

      var updateUnitUserRole = function(unitId, userId, roleId) {
        var postData = {"unitId": parseInt(unitId, 10), "userId": parseInt(userId, 10), "roleId": parseInt(roleId, 10)}
        $.ajax({
          url: '/api/system/unit/set_user_role', type: 'POST', contentType: "application/json", data: JSON.stringify(postData),
          success: function(res){
            layer.closeAll();
            if(res.code === 200){
              layer.msg(res.msg, { icon: 1 });
              table.reloadData(tableId);
            } else {
              layer.alert(res.msg, { icon: 5});
            }
          },
          error: function(res, msg){table.reloadData(userTableId);layer.msg('error');}
        });
      }

      var updateObj = function(postData) {
        $.ajax({
          url: '/api/system/unit/add', type: 'POST', contentType: "application/json", data: JSON.stringify(postData),
          success: function(res){
            layer.closeAll();
            if(res.code === 200){
              layer.msg(res.msg, { icon: 1 });
              treeTable.reload(tableId);
            } else {
              layer.alert(res.msg, { icon: 5});
            }
          },
          error: function(res, msg){treeTable.reload(tableId);layer.msg('error');}
        });
      }

      var removeObj = function(tableObj, postData) {
        $.ajax({
          url: '/api/system/unit/remove', type: 'DELETE', data: postData, success: function(res){
            layer.closeAll();
            if(res.code === 200){
              layer.msg(res.msg, { icon: 1 });
              tableObj.del();
            } else {
              layer.alert(res.msg, { icon: 5});
            }
          },
          error: function(res, msg){layer.msg('error');}
        });
      }

      var getUsersTablse = function(unitId){
        userTable = table.render({
          elem: '#'+userTableId,
          url: '/api/system/unit/user/role',
          response: {statusCode: 200, dataName: 'data'},
          cols: [[
            {type: 'checkbox', templet: '#TPL-userTable-checkbox'},
            {field: 'userId', title: 'id', hide: true},
            {field: 'name', title: '用户名'},
            {field: 'memo', title: '备注'},
            {field: 'roleId', title: 'roleId', templet: '#TPL-select-roles'},
            {field: 'unitId', title: 'unitId'},
          ]],
          parseData: function(res){
            for (let index = 0; index < res.data.length; index++) {
                res.data[index].LAY_CHECKED = unitId == res.data[index].unitId?true:false
            }

            return {
              "code": res.code,
              "msg": res.msg,
              "count": res.data.length,
              "data": res.data
            };
          },
          done: function(res, curr, count){
            // 获取当前行数据 - 自定义方法
            userTable.getRowData = function(tableId, elem){
              var index = $(elem).closest('tr').data('index');
              return treeTable.getNodeDataByIndex(tableId, index) || {};
            };
          }
        });
      }
      
      var manageUsers = function(trData) {
        // 弹出层
        layer.open({
          type: 1,
          area: ['600px', '400px'],
          title: '用户管理 - 单位: ' + trData.unitName,
          content: '<div style="padding: 20px;"><table id="'+userTableId+'"></table></div>',
          btn: ['保存', '取消'],
          success: function(layero, index, that){
            getUsersTablse(trData.unitId);
          },
          yes: function(index, layero){
            var checkedUsers = table.checkStatus(userTableId).data;
            var userIds = checkedUsers.map(user => user.userId);
            console.log(checkedUsers)
            console.log(userIds)
            return
            if(userIds.length > 0){
              $.ajax({
                url: '/api/system/unit/user/assign?unitId=' + trData.unitId,
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify({userIds: userIds}),
                success: function(res){
                  layer.closeAll();
                  if(res.code === 200){
                    layer.msg(res.msg, { icon: 1 });
                  } else {
                    layer.alert(res.msg, { icon: 5});
                  }
                },
                error: function(res, msg){layer.msg('error');}
              });
            } else {
              layer.msg('请选择至少一个用户', { icon: 5});
            }
          }
        });
      }


      var inst = treeTable.render({
        elem: '#'+tableId, 
        toolbar: '#TPL-treeTable-toolbar',
        url: '/api/system/unit/tree',
        tree: {
          customName: {
            children: 'children', name: 'unitName', id: 'unitId', pid: 'parentId', icon: 'icon'
          },
          data: { rootPid: 0 }, 
          view: { icon: 'layui-icon layui-icon-addition' }
        },
        height: 'full', 
        response: {statusCode: 200},
        cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field: 'unitName', title: '单位名称', edit: 'text'},
          {field: 'unitCode', title: '单位代码', edit: 'text'},
          {field: 'unitLogo', title: '单位Logo', edit: 'text'},
          {field: 'unitDbCode', title: '数据库编号', edit: 'text'},
          {field: 'sort', title: '排序', edit: 'text'},
          {field: 'status', title: 'status', width: 100, templet: '#TPL-select-status'},
          {fixed: "right", title: "操作", align: "center", toolbar: "#TPL-treeTable-tools", width: 180} 
        ]],
        page: false,
        done: function(res, curr, count){
          var options = this;

          // 获取当前行数据 - 自定义方法
          inst.getRowData = function(tableId, elem){
            var index = $(elem).closest('tr').data('index');
            return treeTable.getNodeDataByIndex(tableId, index) || {};
          };

          // 单元格编辑事件
          table.on('edit('+ inst.config.id +')', function(obj){
            var field = obj.field; // 得到字段
            var value = obj.value; // 得到修改后的值

            var postData = obj.data; // 得到所在行所有键值
            // 值的校验
            if(field === 'sort'){
              if(!Number(value) == false){
                postData['sort'] = Number(value)
                updateObj(postData);
              }
            } else if (value.length > 0){
              updateObj(postData);
            }
            // 编辑后续操作，如提交更新请求，以完成真实的数据更新
            
          });
          form.on('select(select-status)', function(obj){
            var postData = inst.getRowData(tableId, obj.elem);
            
            postData['status'] = obj.value;

            updateObj(postData);
          });
          form.on('select(select-role)', function(obj){
            var unitId = $(obj.elem).attr('unitId');
            var userId = $(obj.elem).attr('userId')

            updateUnitUserRole(unitId, userId, obj.value)
          });

          treeTable.expandAll(tableId, true);
        }
      });

      // 表头工具栏工具事件
      treeTable.on('toolbar('+tableId+')', function (obj) {
        if (obj.event === 'addRow'){
          var postData = {
            "unitName": "新增单位",
            "unitCode": "",
            "unitLogo": "/img/logo-wiwf.png",
            "unitDbCode": "business",
            "sort": 99,
            "status": 1,
            "parentId": 0
          }
          updateObj(postData);
        }
      });
      // 单元格工具事件
      treeTable.on('tool('+ inst.config.id +')', function (obj) {
        var layEvent = obj.event;
        var trData = obj.data;
        
        if (layEvent === "addChild") {
          var postData = {
            "unitName": "新增单位"+trData.unitId,
            "unitCode": "",
            "unitLogo": "/img/logo-wiwf.png",
            "unitDbCode": "business",
            "sort": 99,
            "status": 1,
            "parentId": trData.unitId
          }
          updateObj(postData);
        } else if (layEvent === 'removeRow'){
          layer.confirm("真的删除 ["+trData.unitName+"]", {title: false}, function (index) {
            removeObj(obj, {id: trData.unitId});
            layer.close(index);
          });
        } else if (layEvent === 'manageUsers') {
          manageUsers(trData);
        }
        
      });
      // 
      getRoles();

    });
  </script>
</body>
</html>